/**
 * @author Irfan
 */
package sg.edu.nus.iss.team4ft.util;

import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class IOService {	
	
	public static void saveToFile(Object[] object, String fileName) throws IOException {
		File file = createFile(fileName);

		FileOutputStream fos = new FileOutputStream(file);
		ObjectOutputStream out = new ObjectOutputStream(fos);
		out.writeObject(object);
		out.close();
		fos.close();
	}
	
	public static Object[] readFromFile(String fileName) throws EOFException, IOException, ClassNotFoundException {
		Object[] output = null;
		FileInputStream fis = new FileInputStream(fileName);
		ObjectInputStream ois = new ObjectInputStream(fis);
		output = (Object[]) ois.readObject();
		ois.close();
		fis.close();
		return output;
	}
	
	public static void saveObjToFile(Object object, String fileName) throws IOException {
		File file = createFile(fileName);

		FileOutputStream fos = new FileOutputStream(file);
		ObjectOutputStream out = new ObjectOutputStream(fos);
		out.writeObject(object);
		out.close();
		fos.close();
	}
	
	public static Object readObjFromFile(String fileName) throws EOFException, IOException, ClassNotFoundException {
		try{
		Object output = null;
		FileInputStream fis = new FileInputStream(fileName);

		ObjectInputStream ois = new ObjectInputStream(fis);
		output = (Object) ois.readObject();
		ois.close();
		fis.close();
		return output;
		}catch (EOFException e) {
			return null;
		}
	}
	
	private static File createFile(String fileName) throws IOException {
		File file = new File(fileName);
		if (!file.isFile())
			file.createNewFile();
		return file;
	}
	
	public static void deleteFile(String fileName){
		File file = new File(fileName);
		if(file.exists()){
			file.delete();
		}
	}
	
	public static Boolean fileExists(String fileName){
		File file = new File(fileName);
		return file.exists();
	}

}
